package org.ns.learn.rpc.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class RpcMessageRequestDecode extends ByteToMessageDecoder {


    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("正在解码！");
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int length = in.readInt();
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        byte[] body = new byte[length];
        in.readBytes(body);
        String json = new String(body, Charset.forName("UTF-8"));
        System.out.println("请求解码:" + json);
        RpcRequest request = JSON.parseObject(json, RpcRequest.class);

        ParameterType[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();

        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameters[i] == null) {
                continue;
            }
            parameters[i] = DecodeUtils.toObject(parameters[i], parameterTypes[i]);
        }
        out.add(request);
    }

}
